package middleware

import (
	"bytes"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Context struct {
	Ctx *gin.Context
}

type responseInfo struct {
	Code int         `json:"code"`
	Msg  interface{} `json:"msg"`
	Data interface{} `json:"data"`
}

type responseBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (r responseBodyWriter) Write(b []byte) (int, error) {
	r.body.Write(b)
	return r.ResponseWriter.Write(b)
}

func (c *Context) Response(code int, msg interface{}, data interface{}) {
	c.Ctx.JSON(http.StatusOK, responseInfo{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

func ResponseLogger() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: ctx.Writer}
		ctx.Writer = w
		ctx.Next()
		fmt.Println("Response body: " + w.body.String())
	}
}
